/*
 * Copyright (C) 2014 naBerTech snc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nabertech.example.android.wearable.sendphoto;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.wearable.view.DelayedConfirmationView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.example.android.wearable.sendphoto.R;
import com.nabertech.example.android.wearable.sendphoto.common.Constants;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.data.FreezableUtils;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Wearable;

import java.io.InputStream;
import java.util.List;

/**
 * Shows photo sent from a paired device.
 *
 * For exercise: notify the paired node when the activity exits.
 */
public class ShowActivity extends Activity implements ConnectionCallbacks,
        OnConnectionFailedListener, DataApi.DataListener,
        DelayedConfirmationView.DelayedConfirmationListener {

    private static final String TAG = "MainActivity";

    // Entry point for Google Play Services.
    private GoogleApiClient mGoogleApiClient;

    // Views.
    private TextView mIntroText;
    private View mLayout;
    private DelayedConfirmationView mDelayedView;

    // Skip timer finish if user select the delayer view.
    private boolean mTimerSelected;

    // Key for source node value.
    public static final String SOURCE_NODE_ID = "source-node-id";

    // Pair node that start the activity.
    private String mSourceNodeId;

    @Override
    public void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.main_activity);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // Get the pair node id.
        Intent myIntent = getIntent();
        mSourceNodeId = myIntent.getStringExtra(SOURCE_NODE_ID);

        setupViews();
        mDelayedView.setListener(this);

        // Create google API Client
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient.isConnected()) {
            Wearable.DataApi.removeListener(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    @Override //ConnectionCallbacks
    public void onConnected(Bundle connectionHint) {
        Log.d(TAG, "Google API Client was connected");
        Wearable.DataApi.addListener(mGoogleApiClient, this);
        sendActivityStartedMessage(mSourceNodeId);
    }

    @Override //ConnectionCallbacks
    public void onConnectionSuspended(int cause) {
        Log.d(TAG, "Connection to Google API client was suspended");
    }

    @Override //OnConnectionFailedListener
    public void onConnectionFailed(ConnectionResult result) {
        Log.e(TAG, "Connection to Google API client has failed");
    }

    @Override //DataListener
    public void onDataChanged(DataEventBuffer dataEvents) {
        Log.d(TAG, "onDataChanged(): " + dataEvents);

        final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
        dataEvents.close();
        for (DataEvent event : events) {
            handleEvent(event);
        }
    }

    private void sendActivityStartedMessage(String node) {
        if (node == null)
            return;

        Log.d(TAG, "sendActivityStartedMessage to: " + node);
        Wearable.MessageApi.sendMessage(
                mGoogleApiClient, node, Constants.SHOW_ACTIVITY_STARTED_PATH, new byte[0])
                .setResultCallback(
                new ResultCallback<MessageApi.SendMessageResult>() {
                    @Override
                    public void onResult(MessageApi.SendMessageResult sendMessageResult) {
                        if (!sendMessageResult.getStatus().isSuccess()) {
                            Log.e(TAG, "Failed to send message with status code: "
                                    + sendMessageResult.getStatus().getStatusCode());
                        }
                    }
                }
        );
    }

    /**
     * Handle the data event.
     */
    private void handleEvent(DataEvent event) {
        if (event.getType() == DataEvent.TYPE_CHANGED) {
            String path = event.getDataItem().getUri().getPath();
            // Check to see if the data change is a new image.
            if (Constants.IMAGE_PATH.equals(path)) {
                DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
                Asset photo = dataMapItem.getDataMap().getAsset(Constants.IMAGE_KEY);
                setPhotoBackGround(photo);
            } else {
                Log.d(TAG, "Unrecognized path: " + path);
            }
        } else if (event.getType() == DataEvent.TYPE_DELETED) {
            Log.d(TAG, "DataItem Deleted: " + event.getDataItem().toString());
        } else {
            Log.d(TAG, "Unknown data event type: " + event.getType());
        }
    }

    /**
     * Set the  {@link com.google.android.gms.wearable.Asset} as the photo background
     */
    private void setPhotoBackGround(Asset photo) {
        Bitmap bitmap = loadBitmapFromAsset(photo);
        setBackGround(bitmap);
    }

    /**
     * Extracts {@link android.graphics.Bitmap} data from the
     * {@link com.google.android.gms.wearable.Asset}
     */
    private Bitmap loadBitmapFromAsset(Asset asset) {
        if (asset == null) {
            throw new IllegalArgumentException("Asset must be non-null");
        }

        InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
                mGoogleApiClient, asset).await().getInputStream();

        if (assetInputStream == null) {
            Log.w(TAG, "Requested an unknown Asset.");
            return null;
        }
        return BitmapFactory.decodeStream(assetInputStream);
    }

    /**
     * Set the {@link android.graphics.Bitmap} image as the photo background
     */
    private void setBackGround(final Bitmap bitmap){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLayout.setBackground(new BitmapDrawable(getResources(),bitmap));
                mIntroText.setText(R.string.i_like_it);

                // Start waiting for user cancel.
                mDelayedView.setVisibility(View.VISIBLE);
                mDelayedView.setTotalTimeMs(5000);
                mTimerSelected = false;
                mDelayedView.start();
            }});
    }

    @Override //DelayedConfirmationListener
    public void onTimerFinished(View view) {
        if (mTimerSelected)
            return;

        sendLikePhotoMessage(mSourceNodeId, true);
        finish();
    }

    @Override //DelayedConfirmationListener
    public void onTimerSelected(View view) {
        mTimerSelected = true;
        mDelayedView.setTotalTimeMs(0);
        mDelayedView.setVisibility(View.GONE);
        mIntroText.setText(R.string.intro);
        sendLikePhotoMessage(mSourceNodeId, false);
    }

    private void sendLikePhotoMessage(String node, boolean result) {
        byte[] message = new byte[1];
        message[0] = result ? Constants.LIKE : Constants.DISLIKE;
        Wearable.MessageApi.sendMessage(
                mGoogleApiClient, node, Constants.LIKE_PHOTO_PATH, message).setResultCallback(
                new ResultCallback<MessageApi.SendMessageResult>() {
                    @Override
                    public void onResult(MessageApi.SendMessageResult sendMessageResult) {
                        if (!sendMessageResult.getStatus().isSuccess()) {
                            Log.e(TAG, "Failed to send message with status code: "
                                    + sendMessageResult.getStatus().getStatusCode());
                        }
                    }
                }
        );
    }

    /**
     * Sets up UI components.
     */
    private void setupViews() {
        mIntroText = (TextView) findViewById(R.id.intro);
        mLayout = findViewById(R.id.layout);
        mDelayedView = (DelayedConfirmationView) findViewById(R.id.delayed_confirmation);
    }
}
